import React from 'react';
import { FormInstance } from 'antd/es/form';
import { Form, Col } from 'antd';
import { defaultColConfig } from './getDefaultSearch';

import classNames from 'classnames';
import { genColumnKey } from '../component/util';
import { IntlType } from '../component/intlContext';
import { ProTableTypes } from '../Table';
import { ProColumns } from '../index';
import { FormInputRender } from './index';
import './index.less';

export type ColConfigProps =
  | {
      xs: number;
      sm: number;
      md: number;
      lg: number;
      xl: number;
      xxl: number;
    }
  | {
      span: number;
    }
  | undefined;

export const proFormItemRender: (props: {
  item: ProColumns<any>;
  isForm: boolean;
  collapse: boolean;
  type: ProTableTypes;
  intl: IntlType;
  formInstance?: Omit<FormInstance, 'scrollToField' | '__INTERNAL__'>;
  colConfig: ColConfigProps;
}) => null | JSX.Element = ({ item, intl, formInstance, collapse, type, isForm, colConfig }) => {
  const {
    valueType,
    dataIndex,
    valueEnum,
    renderFormItem,
    render,
    hideInForm,
    hideInSearch,
    hideInTable,
    renderText,
    order,
    initialValue,
    ellipsis,
    formItemProps,
    index,
    colItemSpan,
    formItemColConfig,
    ...rest
  } = item;
  //外部span
  let span = formItemColConfig ? { ...formItemColConfig } : { ...colConfig };
  const key = genColumnKey(rest.key, dataIndex, index);
  const dom = <FormInputRender item={item} type={type} intl={intl} form={formInstance} />;
  if (!dom) {
    return null;
  }

  // 支持 function 的 title
  const getTitle = () => {
    if (rest.title && typeof rest.title === 'function') {
      return rest.title(item, 'form');
    }
    return rest.title;
  };

  return (
    <Col {...defaultColConfig} {...span} key={key}>
      <Form.Item
        labelAlign="right"
        className={classNames(!collapse && 'form-item-margin-bottom')}
        label={getTitle()}
        name={Array.isArray(dataIndex) ? dataIndex : key}
        {...(isForm && rest)}
      >
        {dom}
      </Form.Item>
    </Col>
  );
};

export default proFormItemRender;
